from google.appengine.ext import db
from os import environ
import webapp2
import jinja2
import os
import captcha
import md5
import session

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))


class User(db.Model):
        username = db.StringProperty(required=True)
        password = db.StringProperty(required=True)
        email = db.StringProperty(required=True)


class Register(webapp2.RequestHandler):
    def post(self):
        challenge = self.request.get('recaptcha_challenge_field')
        response = self.request.get('recaptcha_response_field')
        remoteip = environ['REMOTE_ADDR']

        cResponse = captcha.submit(
            challenge,
            response,
            "6Ledu8oSAAAAADRvkGdUmqMSs828NXPboItSGG1u",
             remoteip
        )

        if cResponse.is_valid:
            user = self.request.get('user')
            passwo = md5.new()
            passwo.update(self.request.get('pass'))
            passw = passwo.hexdigest()
            e_mail = self.request.get('email')
            new_user = User(username=user, password=passw, email=e_mail)
            db.put(new_user)
            self.sess = session.Session('kuli879j')
            expires = 7200
            coo = self.sess.store(user.username, expires)
            self.response.headers.add_header('Set-Cookie', coo)
            texto = "Welcome " + user + "!!!"
        else:
            error = cResponse.error_code
            texto = "error " + error

        template_values = {
            'message': texto,
            'active_user': user,
        }

        template = jinja_environment.get_template('index2.html')
        self.response.out.write(template.render(template_values))


class Login(webapp2.RequestHandler):
    def post(self):
        username = self.request.get('username')
        passwo = md5.new()
        passwo.update(self.request.get('password'))
        passw = passwo.hexdigest()
        query = db.GqlQuery("SELECT * FROM User WHERE username = :name "
                    "AND password = :pwd ",
                    name=username,
                    pwd=passw)

        results = query.get()
        if results is None:
            texto = "Usuario No Encontrado"
            template_values = {
                'message': texto,
            }
            template = jinja_environment.get_template('index.html')
            self.response.out.write(template.render(template_values))
        else:
            user = results
            self.sess = session.Session('kuli879j')
            expires = 7200
            coo = self.sess.store(user.username, expires)
            self.response.headers.add_header('Set-Cookie', coo)
            texto = "Welcome " + user.username
            template_values = {
                'message': texto,
                'active_user': user.username,
            }
            template = jinja_environment.get_template('index2.html')
            self.response.out.write(template.render(template_values))


class Logout(webapp2.RequestHandler):
    def get(self):
        self.sess = session.Session('kuli879j')
        if self.sess.load():
            coo = self.sess.store('', 0)
            self.response.headers.add_header('Set-Cookie', coo)
        texto = ""
        template_values = {
            'message': texto,
        }
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
